namespace DotNetNuke.Common.Utilities
{
    using DotNetNuke.Common;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Security.Permissions;
    using DotNetNuke.Services.FileSystem;
    using DotNetNuke.Services.Localization;
    using ICSharpCode.SharpZipLib.Checksums;
    using ICSharpCode.SharpZipLib.Zip;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Text;
    using System.Web;

    public class FileSystemUtils
    {
        private static string AddFile(string strSourceFile, int PortalId, string HomeDirectory, bool ClearCache)
        {
            return UpdateFile(strSourceFile, strSourceFile, PortalId, HomeDirectory, false, true, ClearCache);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Adds a Folder
        /// </summary>
        /// <param name="_PortalSettings">Portal Settings for the Portal</param>
        /// <param name="parentFolder">The Parent Folder Name</param>
        /// <param name="newFolder">The new Folder Name</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/4/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void AddFolder(PortalSettings _PortalSettings, string parentFolder, string newFolder)
        {
            string ParentFolderName;
            int PortalId;
            DirectoryInfo dinfo = new DirectoryInfo(parentFolder);
            if (_PortalSettings.ActiveTab.ParentId == _PortalSettings.SuperTabId)
            {
                PortalId = Null.NullInteger;
                ParentFolderName = DotNetNuke.Common.Globals.HostMapPath;
            }
            else
            {
                PortalId = _PortalSettings.PortalId;
                ParentFolderName = _PortalSettings.HomeDirectoryMapPath;
            }
            DirectoryInfo dinfoNew = new DirectoryInfo(parentFolder + newFolder);
            if (dinfoNew.Exists)
            {
                throw new ArgumentException(DotNetNuke.Services.Localization.Localization.GetString("EXCEPTION_DirectoryExists"));
            }
            string strResult = dinfo.CreateSubdirectory(newFolder).FullName;
            string FolderPath = "";
            FolderPath = strResult.Substring(ParentFolderName.Length).Replace(@"\", "/");
            AddFolder(PortalId, _PortalSettings.AdministratorRoleId, FolderPath);
        }

        private static int AddFolder(int PortalId, int AdministratorRoleId, string relativePath)
        {
            int FolderID = new FolderController().AddFolder(PortalId, relativePath);
            if (PortalId != Null.NullInteger)
            {
                SetFolderPermissions(PortalId, FolderID, AdministratorRoleId, relativePath);
            }
            return FolderID;
        }

        public static void AddToZip(ref ZipOutputStream ZipFile, string filePath, string fileName, string folder)
        {
            Crc32 crc = new Crc32();
            FileStream fs = File.OpenRead(filePath);
            byte[] buffer = new byte[(Convert.ToInt32(fs.Length) - 1) + 1];
            fs.Read(buffer, 0, buffer.Length);
            ZipEntry entry = new ZipEntry(folder + fileName);
            entry.DateTime = DateTime.Now;
            entry.Size = fs.Length;
            fs.Close();
            crc.Reset();
            crc.Update(buffer);
            entry.Crc = crc.Value;
            ZipFile.PutNextEntry(entry);
            ZipFile.Write(buffer, 0, buffer.Length);
        }

        public static string AddTrailingSlash(string strSource)
        {
            if (!strSource.EndsWith(@"\"))
            {
                strSource = strSource + @"\";
            }
            return strSource;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Copies a File
        /// </summary>
        /// <param name="strSourceFile">The original File Name</param>
        /// <param name="strDestFile">The new File Name</param>
        /// <param name="settings">The Portal Settings for the Portal/Host Account</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/2/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string CopyFile(string strSourceFile, string strDestFile, PortalSettings settings)
        {
            return UpdateFile(strSourceFile, strDestFile, settings.PortalId, settings.HomeDirectoryMapPath, true, false, true);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Deletes a file
        /// </summary>
        /// <param name="strSourceFile">The File to delete</param>
        /// <param name="settings">The Portal Settings for the Portal/Host Account</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Jon Henning]	11/1/2004	Created
        /// [cnurse]        12/6/2004   delete file from db
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string DeleteFile(string strSourceFile, PortalSettings settings)
        {
            return DeleteFile(strSourceFile, settings, true);
        }

        public static string DeleteFile(string strSourceFile, PortalSettings settings, bool ClearCache)
        {
            string retValue = "";
            try
            {
                int PortalId;
                string RootFolderName;
                string strFileName = Path.GetFileName(strSourceFile);
                if (settings.ActiveTab.ParentId == settings.SuperTabId)
                {
                    RootFolderName = DotNetNuke.Common.Globals.HostMapPath;
                    PortalId = Null.NullInteger;
                }
                else
                {
                    RootFolderName = settings.HomeDirectoryMapPath;
                    PortalId = settings.PortalId;
                }
                string SourceFolderName = strSourceFile.Replace(strFileName, "").Replace(RootFolderName, "").Replace(@"\", "/");
                File.Delete(strSourceFile);
                new FileController().DeleteFile(PortalId, strFileName, SourceFolderName, ClearCache);
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                retValue = ex.Message;
                
            }
            return retValue;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Deletes a folder
        /// </summary>
        /// <param name="PortalId">The Id of the Portal</param>
        /// <param name="folder">The Directory Info object to delete</param>
        /// <param name="folderName">The Name of the folder relative to the Root of the Portal</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/4/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void DeleteFolder(int PortalId, DirectoryInfo folder, string folderName)
        {
            folder.Delete(false);
            new FolderController().DeleteFolder(PortalId, folderName.Replace(@"\", "/"));
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Moved directly from FileManager code, probably should make extension lookup more generic
        /// </summary>
        /// <param name="FileLoc">File Location</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Jon Henning]	11/1/2004	Created
        /// [Jon Henning]	1/4/2005	Fixed extension comparison, added content length header - DNN-386
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void DownloadFile(string FileLoc)
        {
            System.IO.FileInfo objFile = new System.IO.FileInfo(FileLoc);
            HttpResponse objResponse = HttpContext.Current.Response;
            if (objFile.Exists)
            {
                string strContentType;
                objResponse.ClearContent();
                objResponse.ClearHeaders();
                objResponse.AppendHeader("content-disposition", "attachment; filename=" + objFile.Name.ToString());
                objResponse.AppendHeader("Content-Length", objFile.Length.ToString());
                string refStringHelperL0 = objFile.Extension;
                if (refStringHelperL0 == ".txt")
                {
                    strContentType = "text/plain";
                }
                else if ((((refStringHelperL0 == ".htm") || (refStringHelperL0 == ".html")) ? 1 : 0) != 0)
                {
                    strContentType = "text/html";
                }
                else if (refStringHelperL0 == ".rtf")
                {
                    strContentType = "text/richtext";
                }
                else if ((((refStringHelperL0 == ".jpg") || (refStringHelperL0 == ".jpeg")) ? 1 : 0) != 0)
                {
                    strContentType = "image/jpeg";
                }
                else if (refStringHelperL0 == ".gif")
                {
                    strContentType = "image/gif";
                }
                else if (refStringHelperL0 == ".bmp")
                {
                    strContentType = "image/bmp";
                }
                else if ((((refStringHelperL0 == ".mpg") || (refStringHelperL0 == ".mpeg")) ? 1 : 0) != 0)
                {
                    strContentType = "video/mpeg";
                }
                else if (refStringHelperL0 == ".avi")
                {
                    strContentType = "video/avi";
                }
                else if (refStringHelperL0 == ".pdf")
                {
                    strContentType = "application/pdf";
                }
                else if ((((refStringHelperL0 == ".doc") || (refStringHelperL0 == ".dot")) ? 1 : 0) != 0)
                {
                    strContentType = "application/msword";
                }
                else
                {
                    if ((refStringHelperL0 == ".csv") || (refStringHelperL0 == ".xls"))
                    {
                    }
                    if (((refStringHelperL0 == ".xlt") ? 1 : 0) != 0)
                    {
                        strContentType = "application/vnd.msexcel";
                    }
                    else
                    {
                        strContentType = "application/octet-stream";
                    }
                }
                objResponse.ContentType = strContentType;
                WriteFile(objFile.FullName);
                objResponse.Flush();
                objResponse.Close();
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the Roles that have a particualr Permission for a Folder
        /// </summary>
        /// <param name="Folder">The Folder</param>
        /// <param name="PortalId">The Id of the Portal</param>
        /// <param name="Permission">The Permissions to find</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string GetRoles(string Folder, int PortalId, string Permission)
        {
            IEnumerator refObjectHelperL0=null;
            StringBuilder Roles = new StringBuilder();
            FolderPermissionCollection objCurrentFolderPermissions = new FolderPermissionController().GetFolderPermissionsCollectionByFolderPath(PortalId, Folder);
            try
            {
                refObjectHelperL0 = objCurrentFolderPermissions.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    FolderPermissionInfo objFolderPermission = (FolderPermissionInfo) refObjectHelperL0.Current;
                    if (objFolderPermission.AllowAccess & (objFolderPermission.PermissionKey == Permission))
                    {
                        Roles.Append(objFolderPermission.RoleName);
                        Roles.Append(";");
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
            return Roles.ToString();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Moves (Renames) a File
        /// </summary>
        /// <param name="strSourceFile">The original File Name</param>
        /// <param name="strDestFile">The new File Name</param>
        /// <param name="settings">The Portal Settings for the Portal/Host Account</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/2/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string MoveFile(string strSourceFile, string strDestFile, PortalSettings settings)
        {
            return UpdateFile(strSourceFile, strDestFile, settings.PortalId, settings.HomeDirectoryMapPath, false, false, true);
        }

        public static string RemoveTrailingSlash(string strSource)
        {
            if (strSource == "")
            {
                return "";
            }
            if (Strings.Mid(strSource, Strings.Len(strSource), 1) == @"\")
            {
                return strSource.Substring(0, Strings.Len(strSource) - 1);
            }
            return strSource;
        }

        public static void SaveFile(string FullFileName, byte[] Buffer)
        {
            if (File.Exists(FullFileName))
            {
                File.SetAttributes(FullFileName, FileAttributes.Normal);
            }
            FileStream fs = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
            fs.Write(Buffer, 0, Buffer.Length);
            fs.Close();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Assigns 1 or more attributes to a file
        /// </summary>
        /// <param name="FileLoc">File Location</param>
        /// <param name="FileAttributesOn">Pass in Attributes you wish to switch on (i.e. FileAttributes.Hidden + FileAttributes.ReadOnly)</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Jon Henning]	11/1/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void SetFileAttributes(string FileLoc, int FileAttributesOn)
        {
            File.SetAttributes(FileLoc, (FileAttributes) FileAttributesOn);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Sets a Folder Permission
        /// </summary>
        /// <param name="PortalId">The Id of the Portal</param>
        /// <param name="FolderId">The Id of the Folder</param>
        /// <param name="PermissionId">The Id of the Permission</param>
        /// <param name="RoleId">The Id of the Role</param>
        /// <param name="relativePath">The folder's Relative Path</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	01/12/2005	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void SetFolderPermission(int PortalId, int FolderId, int PermissionId, int RoleId, string relativePath)
        {
            IEnumerator refObjectHelperL0=null;
            FolderPermissionController objFolderPermissionController = new FolderPermissionController();
            FolderPermissionInfo objFolderPermissionInfo = new FolderPermissionInfo();
            FolderPermissionCollection objCurrentFolderPermissions = objFolderPermissionController.GetFolderPermissionsCollectionByFolderPath(PortalId, relativePath);
            try
            {
                refObjectHelperL0 = objCurrentFolderPermissions.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    objFolderPermissionInfo = (FolderPermissionInfo) refObjectHelperL0.Current;
                    if ((((objFolderPermissionInfo.FolderID == FolderId) & (objFolderPermissionInfo.PermissionID == PermissionId)) & (objFolderPermissionInfo.RoleID == RoleId)) & objFolderPermissionInfo.AllowAccess)
                    {
                        return;
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
            objFolderPermissionInfo = (FolderPermissionInfo) CBO.InitializeObject(objFolderPermissionInfo, typeof(FolderPermissionInfo));
            objFolderPermissionInfo.FolderID = FolderId;
            objFolderPermissionInfo.PermissionID = PermissionId;
            objFolderPermissionInfo.RoleID = RoleId;
            objFolderPermissionInfo.AllowAccess = true;
            objFolderPermissionController.AddFolderPermission(objFolderPermissionInfo);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Sets a Folders Permissions
        /// </summary>
        /// <param name="PortalId">The Id of the Portal</param>
        /// <param name="FolderId">The Id of the Folder</param>
        /// <param name="AdministratorRoleId">The Id of the Administrator Role</param>
        /// <param name="relativePath">The folder's Relative Path</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/4/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void SetFolderPermissions(int PortalId, int FolderId, int AdministratorRoleId, string relativePath)
        {
            IEnumerator refObjectHelperL0=null;
            ArrayList Permissions = new PermissionController().GetPermissionsByFolder(PortalId, "");
            FolderPermissionController objFolderPermissionController = new FolderPermissionController();
            try
            {
                refObjectHelperL0 = Permissions.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    PermissionInfo objPermssionsInfo = (PermissionInfo) refObjectHelperL0.Current;
                    SetFolderPermission(PortalId, FolderId, objPermssionsInfo.PermissionID, AdministratorRoleId, relativePath);
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        public static string StripFolderPath(string strOrigPath)
        {
            if (strOrigPath.IndexOf(@"\") != -1)
            {
                return Strings.Replace(strOrigPath, @"0\", "", 1, 1, CompareMethod.Binary);
            }
            return Strings.Replace(strOrigPath, "0", "", 1, 1, CompareMethod.Binary);
        }

        public static void Synchronize(int PortalId, int AdministratorRoleId, string HomeDirectory)
        {
            string PhysicalRoot = HomeDirectory;
            string VirtualRoot = "";
            SynchronizeFolder(PortalId, AdministratorRoleId, HomeDirectory, PhysicalRoot, VirtualRoot);
            new FileController().GetAllFilesRemoveCache();
        }

        private static void SynchronizeFolder(int PortalId, int AdministratorRoleId, string HomeDirectory, string physicalPath, string relativePath)
        {
            if (Directory.Exists(physicalPath))
            {
                int FolderId = AddFolder(PortalId, AdministratorRoleId, relativePath);
                foreach (string folder in Directory.GetDirectories(physicalPath))
                {
                    string relPath;
                    DirectoryInfo directory = new DirectoryInfo(folder);
                    if (relativePath == "")
                    {
                        relPath = directory.Name;
                    }
                    else
                    {
                        relPath = relativePath + "/" + directory.Name;
                    }
                    SynchronizeFolder(PortalId, AdministratorRoleId, HomeDirectory, folder, relPath);
                }
                foreach (string fileName in Directory.GetFiles(physicalPath))
                {
                    AddFile(fileName, PortalId, HomeDirectory, false);
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Unzips a File
        /// </summary>
        /// <param name="FileLoc">The zip File Name</param>
        /// <param name="DestFolder">The folder where the file is extracted to</param>
        /// <param name="settings">The Portal Settings for the Portal/Host Account</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string UnzipFile(string FileLoc, string DestFolder, PortalSettings settings)
        {
            ZipEntry objZipEntry;
            ZipInputStream objZipInputStream;
            string UnzipFile;
            string strMessage = "";
            PortalController objPortalController = new PortalController();
            string strFileName = "";
            try
            {
                objZipInputStream = new ZipInputStream(File.OpenRead(FileLoc));
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                UnzipFile = ex.Message;
                
                return UnzipFile;
                
            }
            for (objZipEntry = objZipInputStream.GetNextEntry(); objZipEntry != null; objZipEntry = objZipInputStream.GetNextEntry())
            {
                if (objZipEntry.IsDirectory)
                {
                    try
                    {
                        AddFolder(settings, DestFolder, objZipEntry.Name);
                    }
                    catch (Exception exception2)
                    {
                        ProjectData.SetProjectError(exception2);
                        Exception ex = exception2;
                        objZipInputStream.Close();
                        UnzipFile = ex.Message;
                        
                        return UnzipFile;
                        
                    }
                }
            }
            objZipInputStream = new ZipInputStream(File.OpenRead(FileLoc));
            for (objZipEntry = objZipInputStream.GetNextEntry(); objZipEntry != null; objZipEntry = objZipInputStream.GetNextEntry())
            {
                if (!objZipEntry.IsDirectory)
                {
                    if ((((((double) (objPortalController.GetPortalSpaceUsed(settings.PortalId) + objZipEntry.Size)) / 1000000.0) <= settings.HostSpace) | (settings.HostSpace == 0)) | (settings.ActiveTab.ParentId == settings.SuperTabId))
                    {
                        strFileName = Path.GetFileName(objZipEntry.Name);
                        if (strFileName != "")
                        {
                            string strExtension = Path.GetExtension(strFileName).Replace(".", "");
                            if ((Strings.InStr(1, "," + settings.HostSettings["FileExtensions"].ToString().ToLower(), "," + strExtension.ToLower(), CompareMethod.Binary) != 0) | (settings.ActiveTab.ParentId == settings.SuperTabId))
                            {
                                try
                                {
                                    DirectoryInfo Dinfo = new DirectoryInfo(Path.GetDirectoryName(DestFolder + Strings.Replace(objZipEntry.Name, "/", @"\", 1, -1, CompareMethod.Binary)));
                                    if (!Dinfo.Exists)
                                    {
                                        AddFolder(settings, DestFolder, objZipEntry.Name.Substring(0, Strings.Replace(objZipEntry.Name, "/", @"\", 1, -1, CompareMethod.Binary).LastIndexOf(@"\")));
                                    }
                                    FileStream objFileStream = null;
                                    try
                                    {
                                        objFileStream = File.Create(DestFolder + Strings.Replace(objZipEntry.Name, "/", @"\", 1, -1, CompareMethod.Binary));
                                    }
                                    catch (Exception exception3)
                                    {
                                        ProjectData.SetProjectError(exception3);
                                        Exception ex = exception3;
                                        if (objFileStream != null)
                                        {
                                            objFileStream.Close();
                                        }
                                        UnzipFile = ex.Message;
                                        
                                        return UnzipFile;
                                        
                                    }
                                    int intSize = 0x800;
                                    byte[] arrData = new byte[0x801];
                                    for (intSize = objZipInputStream.Read(arrData, 0, arrData.Length); intSize > 0; intSize = objZipInputStream.Read(arrData, 0, arrData.Length))
                                    {
                                        objFileStream.Write(arrData, 0, intSize);
                                    }
                                    objFileStream.Close();
                                    AddFile(DestFolder + Strings.Replace(objZipEntry.Name, "/", @"\", 1, -1, CompareMethod.Binary), settings.PortalId, settings.HomeDirectoryMapPath, false);
                                }
                                catch (Exception exception4)
                                {
                                    ProjectData.SetProjectError(exception4);
                                    Exception ex = exception4;
                                    if (objZipInputStream != null)
                                    {
                                        objZipInputStream.Close();
                                    }
                                    UnzipFile = ex.Message;
                                    
                                    return UnzipFile;
                                    
                                }
                            }
                            else
                            {
                                strMessage = strMessage + "<br>" + string.Format(DotNetNuke.Services.Localization.Localization.GetString("RestrictedFileType"), strFileName, Strings.Replace(settings.HostSettings["FileExtensions"].ToString(), ",", ", *.", 1, -1, CompareMethod.Binary));
                            }
                        }
                    }
                    else
                    {
                        strMessage = strMessage + "<br>" + string.Format(DotNetNuke.Services.Localization.Localization.GetString("DiskSpaceExceeded"), strFileName);
                    }
                }
            }
            objZipInputStream.Close();
            new FileController().GetAllFilesRemoveCache();
            return strMessage;
        }

        public static void UnzipResources(ZipInputStream zipStream, string destPath)
        {
            for (ZipEntry objZipEntry = zipStream.GetNextEntry(); objZipEntry != null; objZipEntry = zipStream.GetNextEntry())
            {
                string LocalFileName = objZipEntry.Name;
                string RelativeDir = Path.GetDirectoryName(objZipEntry.Name);
                if ((((RelativeDir != string.Empty) && !Directory.Exists(Path.Combine(destPath, RelativeDir))) ? 1 : 0) != 0)
                {
                    Directory.CreateDirectory(Path.Combine(destPath, RelativeDir));
                }
                if (((!objZipEntry.IsDirectory && (LocalFileName != "")) ? 1 : 0) != 0)
                {
                    string FileNamePath = Path.Combine(destPath, LocalFileName).Replace("/", @"\");
                    try
                    {
                        if (File.Exists(FileNamePath))
                        {
                            File.SetAttributes(FileNamePath, FileAttributes.Normal);
                            File.Delete(FileNamePath);
                        }
                        FileStream objFileStream = File.Create(FileNamePath);
                        int intSize = 0x800;
                        byte[] arrData = new byte[0x801];
                        for (intSize = zipStream.Read(arrData, 0, arrData.Length); intSize > 0; intSize = zipStream.Read(arrData, 0, arrData.Length))
                        {
                            objFileStream.Write(arrData, 0, intSize);
                        }
                        objFileStream.Close();
                    }
                    catch (Exception exception1)
                    {
                        
                        
                    }
                }
            }
            if (zipStream != null)
            {
                zipStream.Close();
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Updates a File
        /// </summary>
        /// <param name="strSourceFile">The original File Name</param>
        /// <param name="strDestFile">The new File Name</param>
        /// <param name="isCopy">Flag determines whether file is to be be moved or copied</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	12/2/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static string UpdateFile(string strSourceFile, string strDestFile, int PortalId, string HomeDirectory, bool isCopy, bool isNew, bool ClearCache)
        {
            string retValue = "";
            try
            {
                int imageHeight=0;
                int imageWidth=0;
                string strContentType;
                System.IO.FileInfo finfo = new System.IO.FileInfo(strSourceFile);
                string strFileName = Path.GetFileName(strDestFile);
                string strExtension = Path.GetExtension(strFileName).Replace(".", "");
                string refStringHelperL0 = strExtension.ToLower();
                if (refStringHelperL0 == "txt")
                {
                    strContentType = "text/plain";
                }
                else if ((((refStringHelperL0 == "htm") || (refStringHelperL0 == "html")) ? 1 : 0) != 0)
                {
                    strContentType = "text/html";
                }
                else if (refStringHelperL0 == "rtf")
                {
                    strContentType = "text/richtext";
                }
                else if ((((refStringHelperL0 == "jpg") || (refStringHelperL0 == "jpeg")) ? 1 : 0) != 0)
                {
                    strContentType = "image/jpeg";
                }
                else if (refStringHelperL0 == "gif")
                {
                    strContentType = "image/gif";
                }
                else if (refStringHelperL0 == "bmp")
                {
                    strContentType = "image/bmp";
                }
                else if ((((refStringHelperL0 == "mpg") || (refStringHelperL0 == "mpeg")) ? 1 : 0) != 0)
                {
                    strContentType = "video/mpeg";
                }
                else if (refStringHelperL0 == "avi")
                {
                    strContentType = "video/avi";
                }
                else if (refStringHelperL0 == "pdf")
                {
                    strContentType = "application/pdf";
                }
                else if ((((refStringHelperL0 == "doc") || (refStringHelperL0 == "dot")) ? 1 : 0) != 0)
                {
                    strContentType = "application/msword";
                }
                else
                {
                    if ((refStringHelperL0 == "csv") || (refStringHelperL0 == "xls"))
                    {
                    }
                    if (((refStringHelperL0 == "xlt") ? 1 : 0) != 0)
                    {
                        strContentType = "application/x-msexcel";
                    }
                    else
                    {
                        strContentType = "application/octet-stream";
                    }
                }
                if (Convert.ToBoolean(Strings.InStr(1, "jpg,jpeg,jpe,gif,bmp,png,swf,", strExtension.ToLower() + ",", CompareMethod.Binary)))
                {
                    try
                    {
                        Image imgImage = Image.FromFile(strSourceFile);
                        imageHeight = imgImage.Height;
                        imageWidth = imgImage.Width;
                        imgImage.Dispose();
                    }
                    catch (Exception exception1)
                    {
                        
                        strContentType = "application/octet-stream";
                        
                    }
                }
                string SourceFolderName = strSourceFile.Replace(finfo.Name, "").Replace(HomeDirectory, "").Replace(@"\", "/");
                string DestFolderName = strDestFile.Replace(strFileName, "").Replace(HomeDirectory, "").Replace(@"\", "/");
                FileController f = new FileController();
                DataRow[] dr = f.GetAllFiles().Select("FileName='" + strFileName + "' and PortalId " + Interaction.IIf(PortalId == Null.NullInteger, "IS NULL", "=" + PortalId.ToString()).ToString() + " and Folder='" + DestFolderName + "'");
                if ((dr.Length > 0) && !f.FileChanged(dr[0], strFileName, strExtension, finfo.Length, imageWidth, imageHeight, strContentType, DestFolderName))
                {
                    return retValue;
                }
                FileController objFileController = new FileController();
                if (isCopy)
                {
                    finfo.CopyTo(strDestFile);
                    objFileController.AddFile(PortalId, strFileName, strExtension, finfo.Length, imageWidth, imageHeight, strContentType, DestFolderName, ClearCache);
                    return retValue;
                }
                if (isNew)
                {
                    objFileController.AddFile(PortalId, strFileName, strExtension, finfo.Length, imageWidth, imageHeight, strContentType, SourceFolderName, ClearCache);
                }
                else
                {
                    objFileController.UpdateFile(PortalId, finfo.Name, strFileName, strExtension, finfo.Length, imageWidth, imageHeight, strContentType, SourceFolderName, DestFolderName, ClearCache);
                    finfo.MoveTo(strDestFile);
                }
            }
            catch (Exception exception2)
            {
                ProjectData.SetProjectError(exception2);
                Exception ex = exception2;
                retValue = ex.Message;
                
            }
            return retValue;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Writes file to response stream.  Workaround offered by MS for large files
        /// http://support.microsoft.com/default.aspx?scid=kb;EN-US;812406
        /// </summary>
        /// <param name="strFileName">FileName</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Jon Henning]	1/4/2005	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void WriteFile(string strFileName)
        {
            HttpResponse objResponse = HttpContext.Current.Response;
            Stream objStream = null;
            byte[] bytBuffer = new byte[0x2711];
            try
            {
                objStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                long lngDataToRead = objStream.Length;
                objResponse.ContentType = "application/octet-stream";
                while (lngDataToRead > 0L)
                {
                    if (objResponse.IsClientConnected)
                    {
                        int intLength = objStream.Read(bytBuffer, 0, 0x2710);
                        objResponse.OutputStream.Write(bytBuffer, 0, intLength);
                        objResponse.Flush();
                        bytBuffer = new byte[0x2711];
                        lngDataToRead -= intLength;
                    }
                    else
                    {
                        lngDataToRead = -1L;
                    }
                }
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                objResponse.Write("Error : " + ex.Message);
                
            }
            finally
            {
                if (!Information.IsNothing(objStream))
                {
                    objStream.Close();
                }
            }
        }
    }
}

